package com.sukumar.android.backit.receiver;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;

import com.sukumar.android.backit.R;
import com.sukumar.android.backit.activity.BackItPauseActivity;
import com.sukumar.android.backit.bean.BackItRuleBean;
import com.sukumar.android.backit.bean.BackItSMSDataBean;
import com.sukumar.android.backit.db.BackItDBData.BackItRule;
import com.sukumar.android.backit.db.BackItDBData.BackItSMSInbox;
import com.sukumar.android.backit.service.BackItNotifierService;

public class BackItSMSReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		Object pdus[] = (Object[]) bundle.get("pdus");
		SmsMessage smsMessages[] = null;
		if (pdus != null) {
			smsMessages = new SmsMessage[pdus.length];
			for (int n = 0; n < pdus.length; n++) {
				smsMessages[n] = SmsMessage.createFromPdu((byte[]) pdus[n]);
			}
		}
		String smsBody = getSMSInfo(smsMessages);
		BackItRuleBean ruleInfo = checkRuleMatchStatus(smsBody, context);
		if (ruleInfo != null) {
			boolean insertStatus = false;
			if (ruleInfo.getPattern().equals("BING")) {
				insertStatus = insertBingData(smsBody, context);
			} else {
				insertStatus = insertSMSData(smsBody, context);
			}
			if (insertStatus) {
				SharedPreferences sharedpref = PreferenceManager
						.getDefaultSharedPreferences(context);
				boolean notify = sharedpref.getBoolean(
						context.getText(R.string.enable_receiver_key)
								.toString(), false);
				if (notify) {
					sendNotification(context, smsBody, ruleInfo);
					startService(context, ruleInfo);
				}
			}
		}
	}

	private ArrayList<BackItRuleBean> getRulesFromDB(Context context) {
		ArrayList<BackItRuleBean> arrRuleList = new ArrayList<BackItRuleBean>();
		String strWhere = BackItRule.ENABLED + " = \"Y\"";
		Cursor c = context.getContentResolver().query(
				BackItRule.CONTENT_URI,
				new String[] { BackItRule._ID, BackItRule.RULENAME,
						BackItRule.PATTERN, BackItRule.NOTIFURI,
						BackItRule.VIBRATE, BackItRule.ENABLED, BackItRule.REPEAT }, strWhere,
				null, null);
		BackItRuleBean smsRuleBean = null;
		try {
			if (c != null && c.getCount() > 0) {
				c.moveToFirst();
				do {
					smsRuleBean = new BackItRuleBean();
					smsRuleBean.setRuleId(c.getInt(0));
					smsRuleBean.setRuleName(c.getString(1));
					smsRuleBean.setPattern(c.getString(2));
					smsRuleBean.setNotificationUri(c.getString(3));
					smsRuleBean.setVibrate((c.getString(4).equals("Y") ? true
							: false));
					smsRuleBean
							.setRuleEnabled((c.getString(5).equals("Y") ? true
									: false));
					smsRuleBean.setRepeat(c.getInt(6));

					arrRuleList.add(smsRuleBean);
				} while (c.moveToNext());
			}
		} catch (Exception e) {

		} finally {
			c.close();
		}
		return arrRuleList;
	}

	private BackItRuleBean checkRuleMatchStatus(String smsBody, Context context) {
		ArrayList<BackItRuleBean> arrRules = getRulesFromDB(context);
		BackItRuleBean ruleInfo = null;
		for (Iterator<BackItRuleBean> iterator = arrRules.iterator(); iterator
				.hasNext();) {
			ruleInfo = iterator.next();
			if (smsBody.contains(ruleInfo.getPattern())) {
				return ruleInfo;
			}
		}
		return null;
	}

	private boolean insertBingData(String smsBody, Context context) {
		boolean insertStatus = false;
		BackItSMSDataBean bingDets = getBingDetails(smsBody);
		int count = 0;
		boolean insertFlag = true;
		String strWhere = BackItSMSInbox.BINGID + "=?";
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		if (!bingDets.getBingId().equals("-8888")) {
			Cursor c = context.getContentResolver().query(
					BackItSMSInbox.CONTENT_URI,
					new String[] { BackItSMSInbox._COUNT }, strWhere,
					new String[] { bingDets.getBingId() }, null);
			if (c != null && c.getCount() > 0) {
				c.moveToFirst();
				do {
					count = c.getInt(0);
					count++;
					insertFlag = false;
				} while (c.moveToNext());
			}
			c.close();
		}
		if (insertFlag) {
			ContentValues values = new ContentValues();
			values.put(BackItSMSInbox.BINGID, bingDets.getBingId());
			values.put(BackItSMSInbox.RECEPIENT, bingDets.getRecepient());
			values.put(BackItSMSInbox.MESSAGE, bingDets.getMessage());
			values.put(BackItSMSInbox._COUNT, 1);
			values.put(BackItSMSInbox.DATE, sdf.format(new Date()));

			context.getContentResolver().insert(BackItSMSInbox.CONTENT_URI,
					values);
			insertStatus = true;
		} else {
			ContentValues values = new ContentValues();
			values.put(BackItSMSInbox._COUNT, count);
			values.put(BackItSMSInbox.DATE, sdf.format(new Date()));

			context.getContentResolver().update(BackItSMSInbox.CONTENT_URI,
					values, strWhere, new String[] { bingDets.getBingId() });
			insertStatus = true;
		}
		return insertStatus;
	}

	private boolean insertSMSData(String smsBody, Context context) {
		boolean insertStatus = false;
		int count = 0;
		boolean insertFlag = true;
		String strWhere = BackItSMSInbox.MESSAGE + "=?";
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		Cursor c = context.getContentResolver().query(
				BackItSMSInbox.CONTENT_URI,
				new String[] { BackItSMSInbox._COUNT }, strWhere,
				new String[] { smsBody }, null);
		if (c != null && c.getCount() > 0) {
			c.moveToFirst();
			do {
				count = c.getInt(0);
				count++;
				insertFlag = false;
			} while (c.moveToNext());
		}
		c.close();
		if (insertFlag) {
			ContentValues values = new ContentValues();
			values.put(BackItSMSInbox.BINGID, "-8888");
			values.put(BackItSMSInbox.RECEPIENT, "");
			values.put(BackItSMSInbox.MESSAGE, smsBody);
			values.put(BackItSMSInbox._COUNT, 1);
			values.put(BackItSMSInbox.DATE, sdf.format(new Date()));

			context.getContentResolver().insert(BackItSMSInbox.CONTENT_URI,
					values);
			insertStatus = true;
		} else {
			ContentValues values = new ContentValues();
			values.put(BackItSMSInbox._COUNT, count);
			values.put(BackItSMSInbox.DATE, sdf.format(new Date()));

			context.getContentResolver().update(BackItSMSInbox.CONTENT_URI,
					values, strWhere, new String[] { smsBody });
			insertStatus = true;
		}
		return insertStatus;
	}

	private String getSMSInfo(SmsMessage smsMessages[]) {
		String smsBody = "";

		if (smsMessages != null) {
			if (smsMessages.length > 1) {
				SmsMessage smsMsg = smsMessages[0];
				try {
					if (smsMessages.length == 1 || smsMsg.isReplace()) {
						smsBody = smsMsg.getDisplayMessageBody();
					} else {
						StringBuilder bodyText = new StringBuilder();
						for (int i = 0; i < smsMessages.length; i++) {
							bodyText.append(smsMessages[i].getMessageBody());
						}
						smsBody = bodyText.toString();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				smsBody = smsMessages[0].getMessageBody();
			}
		}
		return smsBody;
	}

	private BackItSMSDataBean getBingDetails(String message) {
		BackItSMSDataBean bingDets = new BackItSMSDataBean();
		String strBingId = "-8888";
		String strRecepient = "";
		String strMessage = "";
		boolean failed = false;
		try {
			strBingId = message.substring(message.indexOf("<") + 1,
					message.indexOf(">"));
		} catch (StringIndexOutOfBoundsException e) {
			failed = true;
		}
		bingDets.setBingId(strBingId);
		try {
			strRecepient = message.substring(message.indexOf(">") + 2,
					message.indexOf(">", message.indexOf(">") + 1));
		} catch (StringIndexOutOfBoundsException e) {
			failed = true;
		}
		bingDets.setRecepient(strRecepient);
		try {
			strMessage = message.substring(message.indexOf(">",
					message.indexOf(">") + 1) + 1);
		} catch (StringIndexOutOfBoundsException e) {
			failed = true;
		}
		if (failed) {
			strMessage = message;
		}
		bingDets.setMessage(strMessage);
		return bingDets;
	}

	private void sendNotification(Context pContext, String pNotification,
			BackItRuleBean ruleinfo) {
		NotificationManager notificationManager = (NotificationManager) pContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
		String strTicker = "";

		if (ruleinfo.getPattern().equals("BING")) {
			strTicker = "Received new BING";
		} else {
			strTicker = "Received new alert";
		}

		Notification notification = new Notification(R.drawable.icon,
				strTicker, System.currentTimeMillis());

		notification.defaults |= Notification.DEFAULT_LIGHTS;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		notification.flags |= Notification.FLAG_INSISTENT;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		Intent notificationIntent = new Intent(pContext,
				BackItPauseActivity.class);
		Editor prefEditor = PreferenceManager
		.getDefaultSharedPreferences(pContext).edit();

		if (ruleinfo.getPattern().equals("BING")) {
			prefEditor.remove("view");
			prefEditor.putString("view", "BING");
			prefEditor.commit();
		} else {
			prefEditor.remove("view");
			prefEditor.putString("view", "ALERT");
			prefEditor.commit();
		}
		
		PendingIntent contentIntent = PendingIntent.getActivity(pContext, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(pContext, strTicker, pNotification,
				contentIntent);
		if (ruleinfo.getPattern().equals("BING")) {
			notificationManager.notify(1234, notification);
		} else {
			notificationManager.notify(9999, notification);
		}
	}

	private void startService(Context pContext, BackItRuleBean ruleinfo) {
		@SuppressWarnings("static-access")
		ActivityManager manager = (ActivityManager) pContext
				.getSystemService(pContext.ACTIVITY_SERVICE);
		boolean running = false;
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("com.sukumar.android.sms.SmsNotifierService"
					.equals(service.service.getClassName())) {
				running = true;
			}
		}
		if (!running && ruleinfo.isRuleEnabled()) {
			Intent notificationIntent = new Intent(pContext,
					BackItNotifierService.class);
			notificationIntent.putExtra("URI", ruleinfo.getNotificationUri());
			notificationIntent.putExtra("vibrate", ruleinfo.isVibrate());
			notificationIntent.putExtra("pattern", ruleinfo.getPattern());
			notificationIntent.putExtra("repeat", ruleinfo.getRepeat());
			pContext.startService(notificationIntent);
		}
	}
}
